package yuyicman.utils 
{
	import flash.display.DisplayObject;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;
	import yuyicman.debug.Debugger;
	/**
	 * ...
	 * @author Yuyic.
	 */
	public class MouseSpeedCalculation 
	{
		
		private var _bTime:Number;
		private var _oPosition:Point;
		private var _bPosition:Point;
		private var _container:DisplayObject;
		private var _timeStep:Timer;
		
		public function get oPosition():Point {
			return _oPosition;
		}
		public function get bPosition():Point {
			return _bPosition;
		}
		public function get bTimer():Number {
			return _bTime;
		}
		
		public function get container():DisplayObject {
			return _container;
		}
		
		public function MouseSpeedCalculation( container:DisplayObject ) 
		{
			_container = container;
		}
		
		private function _timeStepHandler( e:TimerEvent ):void {
			_check();
			e.updateAfterEvent();
		}
		
		private function _check():void {
			_bTime = (new Date).getTime();
			_bPosition = new Point( _container.mouseX, _container.mouseY );
		}
		
		public function start():MouseSpeedCalculation {
			_check();
			_oPosition = new Point( _container.mouseX, _container.mouseY );
			_timeStep = new Timer( 100 );
			_timeStep.addEventListener(TimerEvent.TIMER, _timeStepHandler );
			_timeStep.start();
			return this;
		}
		
		public function stop():Object {
			
			var dir:Point = new Point();
			var _ePosition:Point = new Point( _container.mouseX, _container.mouseY );
			var distance:Number = Point.distance( _bPosition, _ePosition );
			
			if ( _ePosition.x > _bPosition.x ) {
				dir.x = 1;
			}
			else if ( _ePosition.x < _bPosition.x ) {
				dir.x = -1;
			}
			
			if ( _ePosition.y > _bPosition.y ) {
				dir.y = 1;
			}
			else if ( _ePosition.y < _bPosition.y ) {
				dir.y = -1;
			}
			
			_bPosition = null;
			_oPosition = null;
			_timeStep.stop();
			_timeStep.removeEventListener(TimerEvent.TIMER, _timeStepHandler);
			_timeStep = null;
			return { spd:distance*1000 / (((new Date).getTime() - _bTime)||1), dir:dir };
		}
		
		public static function initWithContainer( container:DisplayObject ):MouseSpeedCalculation {
			return new MouseSpeedCalculation( container );
		}
		
		public static function startWithContainer( container:DisplayObject ):MouseSpeedCalculation {
			return ( new MouseSpeedCalculation( container ).start() );
		}
		
	}

}